package com.fita.scheduler.service.impl;

import com.demo2do.core.persistence.annotation.Dao;
import com.fita.entity.data.ExchangeRate;
import com.fita.scheduler.dao.ExchangeRateDao;
import com.fita.scheduler.handler.ExchangeRateHandler;
import com.fita.scheduler.service.ExchangeRateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: 11200
 * @date: 2019/8/1
 */
@Service("exchangeRateService")
public class ExchangeRateServiceImpl implements ExchangeRateService {

    @Dao
    private ExchangeRateDao exchangeRateDao;

    private final static String cnyCode = "RMB";

    @Autowired
    private ExchangeRateHandler exchangeRateHandler;

    /**
     * 同步汇率
     */
    public void syncExchangeRate() {

        List<ExchangeRate> exchangeRates = exchangeRateDao.listAllExchangeRateCode();

        List<String> codes = exchangeRates.stream().map(exchangeRate -> exchangeRate.getCurrencyCode()).collect(Collectors.toList());

        List<Map<String, String>> maps = exchangeRateHandler.fetchNewExchangeRate(codes, cnyCode);

        exchangeRates.stream().forEach(exchangeRate -> {
            maps.forEach(map -> {
                boolean b = map.containsKey(exchangeRate.getCurrencyCode().trim());
                if (b){
                    ExchangeRate newExchangeRate = new ExchangeRate();
                    BigDecimal rate = new BigDecimal(map.get(exchangeRate.getCurrencyCode().trim())).divide(new BigDecimal(100));
                    newExchangeRate.create(exchangeRate, rate, 1L);
                    exchangeRateDao.create(newExchangeRate);
                }
            });
        });

    }
}
